package com.das.mechanic_base.widget;

import android.content.Context;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.das.mechanic_base.R;
import com.das.mechanic_base.adapter.alone.X3CameraNewAdapter;
import com.das.mechanic_base.adapter.alone.X3FirstAloneCameraAdapter;
import com.das.mechanic_base.adapter.groundpush.X3FirstCarAdapter;
import com.das.mechanic_base.base.X3BaseBottomSheetDialog;
import com.das.mechanic_base.base.X3IBaseView;
import com.das.mechanic_base.bean.alone.AloneImageAndRecordBean;
import com.das.mechanic_base.bean.camera.CameraBean;
import com.das.mechanic_base.bean.common.AwsFileBean;
import com.das.mechanic_base.bean.create.QuesSystemSnBean;
import com.das.mechanic_base.bean.main.DetectionNewBean;
import com.das.mechanic_base.mapi.api.NetWorkHttp;
import com.das.mechanic_base.mapi.response.HttpCallBack;
import com.das.mechanic_base.mapi.schedulers.RxSchedulersHelper;
import com.das.mechanic_base.utils.X3FileUtils;
import com.das.mechanic_base.utils.X3GlideNewUtils;
import com.das.mechanic_base.utils.X3StringUtils;
import com.das.mechanic_base.utils.X3Utils;
import com.hjq.toast.ToastUtils;
import com.kproduce.roundcorners.RoundButton;
import com.kproduce.roundcorners.RoundImageView;
import com.kproduce.roundcorners.RoundTextView;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

public class X3BottomEditCarDialog extends X3BaseBottomSheetDialog implements View.OnClickListener, X3FirstCarAdapter.IOnSelectFirstCar, X3MemberButtonView.IOnClickAffirm {

    TextView tv_title;
    RecyclerView rlv_item;
    RecyclerView rlv_pic;
    RoundButton rv_end;
    X3MemberButtonView rv_check;
    private X3FirstCarAdapter carAdapter;
    private X3FirstAloneCameraAdapter picAdapter;
    private long receiveBaseId;

    private List<String> sList = new ArrayList<>();
    private List<String> picPaths;

    /**
     * 当前是在拍照操作进来的，还是点击编辑进来的
     */
    private boolean isCamera;
    private String systemSn;

    private IOnTakeCamera iOnTakeCamera;

    /**
     * 损伤部位照片list
     */
    private List<AloneImageAndRecordBean> currentShowList = null;

    /**
     * 在损伤界面开始拍照的时候，是点击第几个icon进行的拍照，当拍照完成后根据这个索引将新数据插入list，对recycleview进行刷新
     */
    private int imageIndex;

    public X3BottomEditCarDialog(@NonNull Context context) {
        super(context);
    }

    @Override
    protected boolean getDialogCancel() {
        return false;
    }

    @Override
    protected void initView() {
        tv_title = getView(R.id.tv_title);
        rlv_item = getView(R.id.rlv_item);
        rlv_pic = getView(R.id.rlv_pic);
        rv_end = getView(R.id.rv_end);
        rv_check = getView(R.id.rv_check);

        rlv_item.setLayoutManager(new LinearLayoutManager(mContext));
        carAdapter = new X3FirstCarAdapter(mContext);
        rlv_item.setAdapter(carAdapter);
        carAdapter.setiOnSelectFirstCar(this);

        configPicRlv();

        rv_end.setOnClickListener(this);
        rv_check.setiOnClickAffirm(this);
        rv_check.changeBtnStatus(true);

        rv_check.changeBtnStatus( false);

    }

    /**
     * 设置顶部图片rlv
     */
    private void configPicRlv(){
        rlv_pic.setLayoutManager(new GridLayoutManager(mContext,3));
        picAdapter = new X3FirstAloneCameraAdapter(mContext,true,0,9);
        rlv_pic.setAdapter(picAdapter);
        picAdapter.setiOnItemCameraClick(new X3FirstAloneCameraAdapter.IOnItemCameraClick(){

            @Override
            public void iOnItemCameraClick(int imageIndex) {
                if (iOnTakeCamera != null){
                    iOnTakeCamera.iOnClickTakeCamera(imageIndex);
                }
            }

            @Override
            public void iOnDeleteClick(long resId, int position, int titleIndex, String path) {
                currentShowList.remove(position);
                picAdapter.changeData(currentShowList);
            }

            @Override
            public void iOnAgainUploadImage(String path, int titleIndex, int imageIndex) {
                savePicture(path);
            }

            @Override
            public void iOnDeleteImage(int titleIndex, List<AloneImageAndRecordBean> mList) {
                currentShowList = mList;
            }
        });

    }

    /**
     * 编辑车损
     * @param systemSn
     * @param paths
     */
    public void showEditCar(String systemSn,List<String> paths,long receiveBaseId,List<String> selectCarList,boolean isCamera) {
        this.picPaths = paths;
        this.isCamera = isCamera;
        this.systemSn = systemSn;
        this.sList = selectCarList;

        if (!isCamera && !X3StringUtils.isListEmpty(paths)){
            showPics(paths,true);
        }

        if (isCamera){
            autoJumpTakePics();
        }

        this.receiveBaseId = receiveBaseId;
        Map<String,Object> map = new HashMap<>();
        map.put("questionToItemSn",systemSn);
        map.put("receiveBaseId",receiveBaseId);

        NetWorkHttp.getApi().getNewQuestionSystemSn(map)
                .compose(((X3IBaseView)mContext).bindToLife())
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .subscribe(new HttpCallBack<QuesSystemSnBean>() {
                    @Override
                    protected void onDone(QuesSystemSnBean quesSystemSnBean) {
                        if (quesSystemSnBean == null) {
                            return;
                        }
                        showCarChoice(quesSystemSnBean);
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {

                    }
                });
    }

    private Handler mHandler = new Handler();

    /**
     * 如果是从拍照进入的则直接调整拍照界面，如果在拍照界面不选取照片则直接关闭当前dialog，
     */
    private void autoJumpTakePics(){
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (iOnTakeCamera != null){
                    iOnTakeCamera.iOnClickTakeCamera(0);
                }
            }
        },50);

    }

    private void showCarChoice(QuesSystemSnBean snBean) {
        tv_title.setText(snBean.itemName);
        List<String> optionsList = snBean.optionsList;
        if (X3StringUtils.isListEmpty(optionsList)) {
            optionsList = new ArrayList<>();
        }
        if (carAdapter != null) {
            carAdapter.changeSelectCar(sList,optionsList);
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.x3_bottom_edit_car_dialog;
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.rv_end) {
            if (iOnEditCar != null) {
                iOnEditCar.iOnEditCarToCamera(sList);
            }
            dismiss();
        }
    }

    /**
     *
     */
    private void showBtnStatus() {
        if (currentShowList == null){
            return;
        }

        boolean isUpLoadDone = true;
        for (AloneImageAndRecordBean bean : currentShowList){
            if (bean.getUploadStatus() != 1){
                isUpLoadDone = false;
                break;
            }
        }
        boolean isSelectType = true;

        if (X3StringUtils.isListEmpty(sList)) {
            isSelectType = false;
        }
        rv_check.changeBtnStatus( isSelectType && isUpLoadDone);
    }

    private void saveEditCarSuccess() {
        rv_check.reset();
        DetectionNewBean.QuestionToItemDetectionBean detectionBean = new DetectionNewBean.QuestionToItemDetectionBean();

        detectionBean.itemUrlList = savePicDownUrl();
        detectionBean.itemName = tv_title.getText().toString();
        detectionBean.sn = systemSn;

        List<DetectionNewBean.QuestionToItemDetectionBean.QuestionListBean> questionListBeans = new ArrayList<>();
        for (int i = 0; i < sList.size(); i++) {
            DetectionNewBean.QuestionToItemDetectionBean.QuestionListBean listBean = new DetectionNewBean.QuestionToItemDetectionBean.QuestionListBean();
            listBean.answer = sList.get(i);
            questionListBeans.add(listBean);
        }
        detectionBean.questionList = questionListBeans;

        if (iOnEditCar != null) {
            iOnEditCar.iOnEditCarSuccess(detectionBean,systemSn);
        }
        dismiss();
    }

    private List<String> savePicDownUrl(){
        List<String> tmp = new ArrayList<>();
        if (!X3StringUtils.isListEmpty(currentShowList)){
            for (AloneImageAndRecordBean bean : currentShowList){
                if (bean.getUploadStatus() == 1){
                    tmp.add(bean.getHttpPath());
                }
            }
        }
        return tmp;
    }

    private void savePicture(String originPath ) {
        try {
            File imgFile = new File(originPath);

            Luban.with(mContext)
                    .load(imgFile.getPath())
                    .ignoreBy(100)
                    .setTargetDir(X3FileUtils.getStoragePath(mContext, X3FileUtils.MECHANIC_PHOTO_STORAGE_PATH))
                    .filter(path1 -> !(TextUtils.isEmpty(imgFile.getPath()) || imgFile.getPath().toLowerCase().endsWith(".gif")))
                    .setCompressListener(new OnCompressListener() {
                        @Override
                        public void onStart() {
                        }

                        @Override
                        public void onSuccess(File file) {
                            upLoadFiles(originPath,file.getPath());
                        }

                        @Override
                        public void onError(Throwable e) {
                        }
                    }).launch();
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void upLoadFiles(String originPath,String compressPath){
        File imgFile = new File(compressPath);

        RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), imgFile);

        String filename = null;
        try {
            filename = URLEncoder.encode(imgFile.getName(), "UTF-8");

            MultipartBody.Part fileBody = MultipartBody.Part.createFormData("multipartFile", filename, requestBody);

            Map<String, RequestBody> map = new HashMap<>();

            map.put("description",RequestBody.create(MediaType.parse("multipart/form-data"), "初检图片"));

            map.put("ossBucketName",RequestBody.create(MediaType.parse("multipart/form-data"), "SERVICE_PIC"));

            NetWorkHttp.getApi().uploadFileAws(map,fileBody,new HashMap<>())
                    .compose(RxSchedulersHelper.defaultComposeRequest())
                    .compose(((X3IBaseView)mContext).bindToLife())
                    .subscribe(new HttpCallBack<AwsFileBean>() {
                        @Override
                        protected void onDone(AwsFileBean awsFileBean) {
                            if (awsFileBean == null) {
                                return;
                            }
                            onUploadDone(awsFileBean,originPath);
                        }

                        @Override
                        protected String LoadingMessage() {
                            return null;
                        }

                        @Override
                        protected void NoNetCallBack() {
                            super.NoNetCallBack();
                            rv_check.reset();
                        }

                        @Override
                        protected void showError(String error) {
                            rv_check.reset();
                        }
                    });

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    IOnEditCar iOnEditCar;

    public X3BottomEditCarDialog setiOnEditCar(IOnEditCar iOnEditCar) {
        this.iOnEditCar = iOnEditCar;
        return this;
    }

    @Override
    public void iOnClickAffirm() {
        saveEditCarSuccess();
    }

    @Override
    public void iOnSelectCar(List<String> sList) {
        this.sList = sList;
        showBtnStatus();
    }

    /**
     * 上传完pic后刷新图片状态
     */
    private void onUploadDone(AwsFileBean awsFileBean,String path){
        List<AloneImageAndRecordBean> mList = new ArrayList<>();
        List<AloneImageAndRecordBean> addImageList = new ArrayList<>();
        addImageList.add(new AloneImageAndRecordBean(path,awsFileBean.downloadUrl,awsFileBean.id,1));
        if (picAdapter == null){
            return;
        }

        /**
         * 不要在这个地方使用
         * List<AloneImageAndRecordBean> mLists = picAdapter.getImageList();
         * 获取list，这样会因为异步造成获得的数据是另一个线程add或者remove或者clear的list数据，会出现数据不准确
         * 可以考虑使用同步锁
         */
        if (currentShowList == null || currentShowList.size() == 0){
            mList = addImageList;
        } else {
            int mCurrent = -1;
            for(int i = 0; i < currentShowList.size(); i++){
                if (currentShowList.get(i).getId() > 0){
                    if (currentShowList.get(i).getPath().equals(path) && currentShowList.get(i).getId() == awsFileBean.id) {
                        Log.e("edite_pic","修改相同的图片 = " + currentShowList.get(i).getPath());

                        mCurrent = i;
                        break;
                    }
                } else {
                    if (currentShowList.get(i).getPath().equals(path)) {
                        mCurrent = i;
                        break;
                    }
                }
            }
            if(mCurrent == -1){
                return;
            }
            currentShowList.remove(mCurrent);
            currentShowList.add(mCurrent,new AloneImageAndRecordBean(path,awsFileBean.downloadUrl,awsFileBean.id,1));
            mList = currentShowList;
        }
        showBtnStatus();
        picAdapter.changeData(mList);
    }

    /**
     * 拍照返回的照片数据
     * @param cameraBean
     */
    public void onGetPicRefreshPicRlv(CameraBean cameraBean,int imageIndex){
        this.imageIndex = imageIndex;
        List<String> pList = (List<String>) cameraBean.cameraData;
        showPics(pList,false);
    }

    /**
     *
     * @param pList
     * @param isPicUpLoaded 图片是否已经上传完成，从编辑进来的图片其状态为上传完成，
     */
    private void showPics( List<String> pList,boolean isPicUpLoaded){
        List<AloneImageAndRecordBean> addImageList = new ArrayList<>();
        if (pList != null && pList.size() > 0){
            for (String path : pList){
                if (isPicUpLoaded){
                    addImageList.add(new AloneImageAndRecordBean(path,path,0,1));
                } else {
                    addImageList.add(new AloneImageAndRecordBean(path,path,0,0));
                    savePicture(path);
                }
            }
        }
        if (currentShowList == null){
            currentShowList = addImageList;
        }else{
            currentShowList.addAll(addImageList);
        }
        picAdapter.changeData(currentShowList);
    }

    public interface IOnEditCar {

        // 点击返回需要重新拍照
        void iOnEditCarToCamera(List<String> sList);

        // 重新拍照
        void iOnEditCarCameraAgain(String sn,List<String> sList);

        // 编辑成功需要更新之前的数据
        void iOnEditCarSuccess(DetectionNewBean.QuestionToItemDetectionBean detectionBean,String sn);
    }

    public interface IOnTakeCamera {
        void iOnClickTakeCamera(int imageIndex);
    }

    public IOnTakeCamera getiOnTakeCamera() {
        return iOnTakeCamera;
    }

    public void setiOnTakeCamera(IOnTakeCamera iOnTakeCamera) {
        this.iOnTakeCamera = iOnTakeCamera;
    }
}
